﻿using AutoMapper;
using Ross.EntityFramework;
using Ross.EntityFramework.Model;
using Ross.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Ross.Service
{
    public class CourseService : BaseService, IDisposable
    {
        private TranDbContext dbContext;
        public IRepository<Course, long> repository;
        private CoursewareService courseware;
        private SignsService signup;
        public CourseService(string nameOrConnectionString)
        {
            dbContext = new TranDbContext(nameOrConnectionString);
            courseware = new CoursewareService(nameOrConnectionString);
            signup = new SignsService(nameOrConnectionString);
            repository = new Repository<Course, long>(dbContext);
        }
        /// <summary>
        /// 添加课程
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public ResultDto<bool> Create(Dto.Course dto)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            var obj = repository.GetAllList(o => o.Title == dto.Title).Count;
            if (obj > 0)
            {
                result.message = "Course is exist";
                result.status = 500;
                result.datas = false;
            }
            else
            {
                try
                {
                    Course model = new Course();
                    model = Mapper.Map<Course>(dto);
                    model.ClassID = string.Join(",", dto.ClassID);
                    if (dto.DateRange.Length > 1)
                    {
                        model.CreateTime = DateTime.Parse(dto.DateRange[0]);
                        model.EndTime = DateTime.Parse(dto.DateRange[1]);
                    }
                    repository.Insert(model);
                    result.datas = true;
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.datas = false;
                    result.status = 500;
                }
            }
            return result;
        }
        //编辑
        public ResultDto<bool> Update(Dto.Course course)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                //var obj = repository.GetAllList(o => (o.Title == course.Title) && o.ID != course.ID).FirstOrDefault();
                var obj = repository.GetAllList(o => (o.Title == course.Title) && o.ID != course.ID).FirstOrDefault();
                if (obj == null)
                {
                    var model = repository.Get(course.ID);
                    model.Title = course.Title;
                    model.Intro = course.Intro;
                    model.ClassID = string.Join(",", course.ClassID);
                    model.CType = course.CType;
                    model.ImgURL = course.ImgURL;
                    model.VedioURL = course.VedioURL;
                    model.FileURL = course.FileURL;
                    model.InActive = course.InActive;
                    model.Contents = course.Contents;
                    model.UserID = course.UserID;
                    model.UserName = course.UserName;
                    model.SignNum = course.SignNum;
                    model.CreateTime = DateTime.Parse(course.DateRange[0]);
                    model.EndTime = DateTime.Parse(course.DateRange[1]);
                    model.Rate = course.Rate;
                    model.Points = course.Points;
                    model.Times = course.Times;
                    repository.Update(model);
                    result.status = 200;
                    result.datas = true;
                }
                else
                {
                    result.message = "This title has been used in another course";
                    result.status = 500;
                    result.datas = false;
                }
            }
            catch (Exception ex)
            {
                result.status = 500;
                result.message = Common.GetInnerException(ex);
            }
            return result;
        }

        public ResultDto<bool> UpdateByID(Dto.Course course)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                var model = repository.Get(course.ID);
                model.ImgURL = course.ImgURL;
                repository.Update(model);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.status = 500;
                result.message = Common.GetInnerException(ex);
            }
            return result;
        }
        //删除
        public ResultDto<bool> Delete(long id)
        {
            ResultDto<bool> result = new ResultDto<bool>();
            try
            {
                repository.Delete(id);
                result.status = 200;
                result.datas = true;
            }
            catch (Exception ex)
            {
                result.message = ex.Message;
                result.status = 500;
                result.datas = false;
            }
            return result;
        }
        /// <summary>
        /// 分页获取课程
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="keywords"></param>
        /// <param name="classid"></param>
        /// <param name="cType"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResultDto<List<Dto.Course>> GetPageList(int pageindex = 1, int pagesize = 10, string keywords = "", string classid = "",string cType = "",long userId=0)
        {
            ResultDto<List<Dto.Course>> result = new ResultDto<List<Dto.Course>>();
            Expression<Func<Course, bool>> expression = o => o.ID > 0;
            if (!string.IsNullOrEmpty(keywords))
                expression = expression.ExpressionAnd(t => t.Title.Contains(keywords));
            if (!string.IsNullOrEmpty(classid))
                expression = expression.ExpressionAnd(t => t.ClassID.Contains(classid));
            if (!string.IsNullOrEmpty(cType))
                expression = expression.ExpressionAnd(t => t.CType == cType);
            if (userId != 0)
                expression = expression.ExpressionAnd(t => t.UserID == userId);

            var resp = repository.GetPageList(pageindex, pagesize, expression);            
            result = Mapper.Map<ResultDto<List<Dto.Course>>>(resp);
            foreach (Dto.Course item in result.datas)
            {
                var obj = resp.datas.Where(o => o.ID == item.ID).FirstOrDefault();
                item.DateRange = new string[] { obj.CreateTime.ToShortDateString(), obj.EndTime.ToShortDateString() };
                item.ClassID = obj.ClassID.Split(',');
            }
            return result;
        }
        /// <summary>
        /// 获取用户报名的课程
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public ResultDto<List<Dto.Course>> GetSignCourse(int pageindex = 1, int pagesize = 10, long userId = 0)
        {
            ResultDto<List<Dto.Course>> result = new ResultDto<List<Dto.Course>>();            
            var signups = signup.GetAllSignByUser(userId);
            if(signups.datas!=null)
            {
                long[] CourseIDArr = signups.datas.Select(o => o.CourseID).ToArray();
                Expression<Func<Course, bool>> expression = o => CourseIDArr.Contains(o.ID);
                var resp = repository.GetPageList(pageindex, pagesize, expression);
                result = Mapper.Map<ResultDto<List<Dto.Course>>>(resp);
                foreach (Dto.Course item in result.datas)
                {
                    var obj = resp.datas.Where(o => o.ID == item.ID).FirstOrDefault();
                    item.ClassID = obj.ClassID.Split(',');
                }
            }            
            return result;
        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultDto<Dto.Course> GetById(long id)
        {
            ResultDto<Dto.Course> result = new ResultDto<Dto.Course>();
            result.status = 500;
            try
            {
                Course resp = repository.Get(id);
                if (resp != null)
                {
                    var obj = Mapper.Map<Dto.Course>(resp);
                    var cscResp = courseware.GetAllList(obj.ID);
                    string FileUrls = "";
                    if (cscResp.status == 200)
                    {
                        List<Dto.FileObj> files = new List<Dto.FileObj>();
                        foreach(var item in cscResp.datas)
                        {
                            files.Add(new Dto.FileObj
                            {
                                name = item.Title,
                                uid = item.ID.ToString(),
                                url = item.FileURL
                            });
                        }
                        FileUrls = JsonConvert.SerializeObject(files);
                    }
                    obj.FileURL = FileUrls;
                    obj.DateRange = new string[] { resp.CreateTime.ToShortDateString(), resp.EndTime.ToShortDateString() };
                    obj.ClassID = resp.ClassID.Split(',');
                    result.datas = obj;
                    result.status = 200;
                    result.message = "ok";
                }
            }
            catch(Exception ex)
            {
                result.message = ex.Message;
            }
            return result;
        }
        //获取列表
        public ResultDto<List<Dto.Course>> GetAllList()
        {
            ResultDto<List<Dto.Course>> result = new ResultDto<List<Dto.Course>>();
            var lists = repository.GetAllList();
            result.datas = Mapper.Map<List<Dto.Course>>(lists);
            return result;
        }
        //评分
        public ResultDto<bool> Score(Dto.Course course) {
            ResultDto<bool> result = new ResultDto<bool>();
            var obj = repository.Get(course.ID);
            if (obj == null)
            {
                result.message = "course is not exist";
                result.status = 500;
                result.datas = false;
            }
            else
            {
                try
                {
                    obj.Rate = course.Rate;
                    repository.Update(obj);
                    result.datas = true;
                }
                catch (Exception ex)
                {
                    result.message = ex.Message;
                    result.datas = false;
                    result.status = 500;
                }
            }
            return result;
        }
        public void Dispose()
        {
            dbContext.Dispose();
        }
        

    }
}
